<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-8">
      <div>
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white">套餐价格管理</h1>
        <p class="text-gray-600 dark:text-gray-400 mt-2">管理会员套餐和价格方案</p>
      </div>
      <button
        @click="showCreateModal = true"
        class="btn btn-primary flex items-center gap-2"
      >
        <Icon name="heroicons:plus" class="w-5 h-5" />
        新增套餐
      </button>
    </div>

      <!-- 套餐列表 -->
      <div v-if="loading" class="text-center py-12">
        <Icon name="line-md:loading-loop" class="w-12 h-12 text-blue-600 mx-auto" />
        <p class="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
      </div>

      <div v-else class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <div
          v-for="plan in plans"
          :key="plan.id"
          class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6"
        >
          <div class="flex justify-between items-start mb-4">
            <div>
              <h3 class="text-xl font-bold text-gray-900 dark:text-white">{{ plan.name }}</h3>
              <p class="text-sm text-gray-500">{{ plan.type }} - {{ plan.duration }}个月</p>
            </div>
            <span
              :class="plan.isActive ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'"
              class="px-2 py-1 text-xs rounded-full"
            >
              {{ plan.isActive ? '启用' : '禁用' }}
            </span>
          </div>

          <div class="mb-4">
            <span class="text-3xl font-bold text-blue-600">¥{{ plan.price }}</span>
          </div>

          <div class="mb-4 space-y-1">
            <p v-for="feature in plan.features" :key="feature" class="text-sm text-gray-600 dark:text-gray-400">
              {{ feature }}
            </p>
          </div>

          <div class="flex gap-2">
            <button
              @click="editPlan(plan)"
              class="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              ✏️ 编辑
            </button>
            <button
              @click="deletePlan(plan.id)"
              class="px-3 py-2 border border-red-300 text-red-600 rounded-lg hover:bg-red-50"
            >
              🗑️
            </button>
          </div>
        </div>
      </div>

      <!-- 创建/编辑模态框 -->
      <div
        v-if="showCreateModal || showEditModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
        @click.self="closeModal"
      >
        <div class="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
          <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">
            {{ showEditModal ? '编辑套餐' : '新增套餐' }}
          </h2>

          <form @submit.prevent="savePlan" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">套餐名称</label>
              <input
                v-model="formData.name"
                type="text"
                required
                class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                placeholder="例如：基础会员（月度）"
              />
            </div>

            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">套餐类型</label>
                <select
                  v-model="formData.type"
                  required
                  class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                >
                  <option value="basic">基础会员</option>
                  <option value="premium">高级会员</option>
                </select>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">时长（月）</label>
                <input
                  v-model.number="formData.duration"
                  type="number"
                  required
                  min="1"
                  class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                  placeholder="1"
                />
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">价格（元）</label>
              <input
                v-model.number="formData.price"
                type="number"
                required
                min="0"
                step="0.01"
                class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                placeholder="19.9"
              />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">功能列表（每行一个）</label>
              <textarea
                v-model="featuresText"
                rows="6"
                class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                placeholder="✓ 无广告浏览&#10;✓ 收藏 100 个工具&#10;✓ 高级搜索功能"
              ></textarea>
            </div>

            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">排序</label>
                <input
                  v-model.number="formData.sort"
                  type="number"
                  class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                  placeholder="0"
                />
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">状态</label>
                <select
                  v-model="formData.isActive"
                  class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                >
                  <option :value="true">启用</option>
                  <option :value="false">禁用</option>
                </select>
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">描述（可选）</label>
              <textarea
                v-model="formData.description"
                rows="2"
                class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                placeholder="套餐描述..."
              ></textarea>
            </div>

            <div class="flex gap-4 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="saving"
                class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              >
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

definePageMeta({
  layout: 'admin',
  middleware: ['auth'],
})

const $api = useNuxtApp().$api
const toast = useToast()

const loading = ref(true)
const saving = ref(false)
const plans = ref<any[]>([])
const showCreateModal = ref(false)
const showEditModal = ref(false)
const editingPlan = ref<any>(null)

const formData = ref({
  name: '',
  type: 'basic',
  price: 0,
  duration: 1,
  features: [] as string[],
  isActive: true,
  sort: 0,
  description: '',
})

const featuresText = computed({
  get: () => formData.value.features.join('\n'),
  set: (value: string) => {
    formData.value.features = value.split('\n').filter(line => line.trim())
  }
})

onMounted(async () => {
  await loadPlans()
})

const loadPlans = async () => {
  loading.value = true
  try {
    plans.value = await $api('/subscriptions/admin/plans') as any[]
  } catch (error: any) {
    console.error('加载套餐失败:', error)
    toast.error('加载套餐失败')
  } finally {
    loading.value = false
  }
}

const editPlan = (plan: any) => {
  editingPlan.value = plan
  formData.value = {
    name: plan.name,
    type: plan.type,
    price: plan.price,
    duration: plan.duration,
    features: [...plan.features],
    isActive: plan.isActive,
    sort: plan.sort,
    description: plan.description || '',
  }
  showEditModal.value = true
}

const savePlan = async () => {
  saving.value = true
  try {
    if (showEditModal.value && editingPlan.value) {
      // 更新
      await $api(`/subscriptions/admin/plans/${editingPlan.value.id}`, {
        method: 'PUT',
        body: formData.value,
      })
      toast.success('套餐更新成功')
    } else {
      // 创建
      await $api('/subscriptions/admin/plans', {
        method: 'POST',
        body: formData.value,
      })
      toast.success('套餐创建成功')
    }
    
    closeModal()
    await loadPlans()
  } catch (error: any) {
    console.error('保存套餐失败:', error)
    toast.error(error?.data?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const deletePlan = async (id: number) => {
  if (!confirm('确定要删除这个套餐吗？')) return

  try {
    await $api(`/subscriptions/admin/plans/${id}`, {
      method: 'DELETE',
    })
    toast.success('删除成功')
    await loadPlans()
  } catch (error: any) {
    console.error('删除失败:', error)
    toast.error('删除失败')
  }
}

const closeModal = () => {
  showCreateModal.value = false
  showEditModal.value = false
  editingPlan.value = null
  formData.value = {
    name: '',
    type: 'basic',
    price: 0,
    duration: 1,
    features: [],
    isActive: true,
    sort: 0,
    description: '',
  }
}
</script>

